package com.tc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tc.domain.Menu;
import com.tc.domain.User;
import com.tc.mapper.MenuMapper;
import com.tc.mapper.RolemenuMapper;
import com.tc.mapper.UserMapper;
import com.tc.service.UserService;
import com.tc.utils.ResultVo;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private RolemenuMapper rolemenuMapper;
    @Autowired
    private MenuMapper menuMapper;

    public ResultVo<User> login(String username, String password) throws Exception {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("username", username);
        qw.eq("password", password);
        User user = getOne(qw);
        System.out.println(user);
        if (user != null) {
            if (user.getIsDeleted() == 0) {
                QueryWrapper listRoleQw = new QueryWrapper<>();
                listRoleQw.eq("role_id", user.getRoleId());
                listRoleQw.select("menu");
                List<Integer> menuIds = rolemenuMapper.selectObjs(listRoleQw);

                List<Menu> menus = menuMapper.selectBatchIds(menuIds);

                for (Menu menu : menus) {
                    QueryWrapper listMenuQw = new QueryWrapper<>();
                    listMenuQw.eq("parent_id", menu.getId());
                    menu.setChildren(menuMapper.selectList(listMenuQw));
                }
                user.setMenuList(menus);
                HashMap<String, Object> map = new HashMap<>();

                JwtBuilder builder = Jwts.builder();
                String token = builder.setSubject(username)
                        .setIssuedAt(new Date())
                        .setId(user.getId().toString())
                        .setClaims(map)
                        .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24))
                        .signWith(SignatureAlgorithm.HS256, "yyzx")
                        .compact();
                return ResultVo.ok(user, token);
            }
            return ResultVo.fail("无权限");
        }
        return ResultVo.fail("用户名或密码错误");
    }
}
